package com.dianqiu.base.util;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DateUtil {
	private static Logger logger = LoggerFactory.getLogger(DateUtil.class);
	private static final Map<String, SimpleDateFormat> sdfMap = new HashMap<String, SimpleDateFormat>();
	public static Date formatStr2Date(String time,String pattern) throws ParseException{
		SimpleDateFormat sdf = null;
		if (sdfMap.containsKey(pattern)) {
			sdf = sdfMap.get(pattern);
		}else {
			
			sdf = new SimpleDateFormat(pattern);
			sdfMap.put(pattern, sdf);
		}
		Date parse = sdf.parse(time);
		return parse;
	}
	
	public static Timestamp formatStr2Timestamp(String time,String pattern){
		logger.info("Begin to format time string <"+time+"> to <"+pattern+"> pattern");
		Date temp;
		try {
			temp = formatStr2Date(time, pattern);
			if (temp != null) {
				return new Timestamp(temp.getTime());
			}
		} catch (ParseException e) {
			logger.error("format time string <"+time+"> to <"+pattern+"> pattern hit parse error");
			logger.error(e.getMessage(), e);
		}
		return null;
	}
	
}
